package com.zhengzengliang.jwt.controller;

import com.zhengzengliang.jwt.result.ResultObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class LoginController {

    private final Map<String, String> map = new ConcurrentHashMap<>();

    @PostMapping("/app/login")
    public ResultObject login(String name, String pwd){
        ResultObject ro = new ResultObject();

        // 验证输入是否为空
        if (name == null || name.trim().isEmpty() || pwd == null || pwd.trim().isEmpty()) {
            ro.setCode(1);
            ro.setMsg("用户名和密码不能为空");
            ro.setData("");
            return ro;
        }

        // 验证用户名和密码
        if (name.equals("lisi") && "123".equals(pwd)) {
            // 登录成功
            String token = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
            map.put(token, name);
            ro.setCode(0);
            ro.setMsg("登录成功");
            ro.setData(token);
            System.out.println("login token=" + token);
        } else {
            // 登录失败
            ro.setCode(1);
            ro.setMsg("用户名或密码错误");
            ro.setData("");
        }
        return ro;
    }

    @PostMapping("/app/query")
    public ResultObject query(String accessToken){
        System.out.println("accessToken=" + accessToken);
        ResultObject ro = new ResultObject();

        if (map.containsKey(accessToken)) {
            ro.setCode(0);
            ro.setMsg("用户已经登录，可以执行查询");
            ro.setData("查询李四");
        } else {
            ro.setCode(1);
            ro.setMsg("未登录或会话已过期");
            ro.setData("");
        }
        return ro;
    }
}
